import React, { useState, useEffect, useContext, useRef } from "react";
import ProgressSlider from '@/components/progress_slider/index'
import moment from 'moment'
import Lyricpage from '@/pages/lyricpage/index'
import SonglistForPlay from '../songlistForPlay/index'
import { Avatar, Tooltip } from "antd";
import { UserOutlined } from "@ant-design/icons";
import { getSongdetailByids, getsongUrl } from '@/api'
import MyContent from "@/store/my-context";
import IconFont from "../iconfont";
import styles from "./footer.less";
import { changePlayingSong } from '@/store/functions'
// const BrowserWindow = require('electron').remote.BrowserWindow

const Footer: React.FC = () => {
// const { ipcRenderer } = require('electron').default
  const { state, dispatch } = useContext(MyContent);
  const [progress, setProgress] = useState<number>(0)
  const [voProg, setVoProg] = useState<number>(1)//音量进度条
  const [songDetail, setSongDetail] = useState<any>(null)
  const [isLike, setIsLike] = useState<boolean>(false)
  const [isMuted, setIsMuted] = useState<boolean>(false)
  const [songUrl, setSongUrl] = useState<string | null>(null)
  const [changeType, setChangeType] = useState<number>(0)
  const [lyricIsOpen, setLyricIsOpen] = useState<boolean>(false)
  const arrChangeTypes =
    [{
      text: '顺序播放', iconType: "iconxunhuan", nextCount: () => {
        return 1
      }
    },
    {
      text: '列表循环', iconType: "iconxunhuan", nextCount: () => {
        return 1
      }
    },
    {
      text: '单曲循环', iconType: "iconxunhuan", nextCount: () => {
        return 0
      }
    },//表示特殊处理
    {
      text: '随机播放', iconType: "iconxunhuan", nextCount: () => {
        return Math.floor((state.songsInfoPlay.length - 1) * Math.random())
          || 1
      }
    }//特殊处理
    ]
  const volumeProgressChange = (volumeProgress: number) => {
    audioEle?.current?.volume >= 0
      && (audioEle.current.volume = volumeProgress)
    volumeProgress === 0 ?
      (setIsMuted(true)) : (setIsMuted(false))
    setVoProg(volumeProgress)
  }
  const changeSong = (isNext: boolean) => {
    if (state?.songsInfoPlay?.length > 0) {
      let changCount: number = isNext ? 1 : -1
      changCount = arrChangeTypes[changeType].nextCount() * changCount
      if(changCount){
        changePlayingSong(changCount, state)?.then((res) => {
          if (res) { dispatch(res) }
        }).catch((err) =>
          console.error(err)
        )
      }else{
       changeCurrentTime(0)
      }
    }
  }
  const audioEle = useRef<any>(null);
  const onTimeUpdate = () => {
    let time = audioEle?.current?.currentTime || 0
    setProgress(time / audioEle?.current?.duration
      || 0)
    dispatch({ type: 'SET_CURRENTTIME', value: { currentTime: time } })
  }
  const changeCurrentTime = (tprogress: number) => {
    if (audioEle?.current?.duration > 0) {
      audioEle.current.currentTime = tprogress * audioEle.current.duration
      setProgress(tprogress)
    }
  }
  //audio初始化，调节音量
  useEffect(() => {
    console.log('audio初始化');
    console.log()
    if (audioEle?.current) {
      audioEle.current.volume = isMuted ? 0 : voProg
    }
  }, [audioEle])
  useEffect(() => {
    if (state.playInfo.playingId > 0) {
      let thisId: number | null = state.playInfo.playingId
      getsongUrl({ id: thisId }).then((res) => {
        console.log(res?.data[0])
        if (res?.data?.length > 0 && res?.data[0]?.url) {
          setSongUrl(res.data[0].url)
          audioEle.current.play();
        }else{
          console.error('footer getsongUrl出错');
        }
      })
      getSongdetailByids({ ids: thisId }).then(detail => {
        if (detail?.songs.length > 0) {
          setSongDetail(detail?.songs[0])
          console.log(detail?.songs[0])
        } else {
          console.error('footer getSongDetail失败')
        };
      }).catch((err) => {
        console.log(err);
      })
    } else {
      setSongDetail(null)
      setSongUrl(null)
    }
  }, [state.playInfo.playingId])
  return (
    <div className={styles["footer-wrap"]}>

      <SonglistForPlay />
        <Lyricpage isDisplay = {lyricIsOpen && songDetail}
        />
      <div className={styles["footer-left"]}>
        {songDetail &&//没有歌曲播放时隐藏
          (<>
            <a
              className={styles['lyric-open-close']}
              onClick={() => {
                let tIsOpen: boolean = !lyricIsOpen
                setLyricIsOpen(tIsOpen)
              }}>
              <Avatar
                shape="square"
                size={50}
                src={songDetail?.al?.picUrl}
                icon={<UserOutlined />}
                className={styles['song-cover']}
              >
              </Avatar>
              <div className={styles['div-background']}>
                <IconFont
                  type={lyricIsOpen
                    ? 'iconyoushangjiantou'
                    : 'iconzuoxiajiantou'}
                  className={styles['arrow-left-bottom']}
                />
                <IconFont
                  type={lyricIsOpen
                    ? 'iconzuoxiajiantou'
                    : 'iconyoushangjiantou'}
                  className={styles['arrow-right-top']}
                />
              </div>

            </a>

            <div className={styles["music-title-wrap"]}>
              <p>
                <a style={{
                  fontSize: '16px',
                  color: 'rgb(54,54,54)'
                }}>
                  {songDetail?.name}
                </a>
                <IconFont onClick={() => { setIsLike(!isLike) }
                }
                  style={isLike
                    ? {
                      fontSize: '16px',
                      marginLeft: '20px',
                      color: 'rgb(236,65,65)'
                    }
                    : {
                      fontSize: '16px',
                      marginLeft: '20px'
                    }}
                  type={isLike
                    ? "iconaixin"
                    : 'iconaixin1'
                  }
                />
              </p>
              <p>
                <span>{songDetail?.ar[0]?.name}</span>
              </p>
            </div>
          </>)

        }
      </div>
      <div className={styles["footer-center"]}>
        <div className={styles["music-control"]}>
          <div className={styles["music-control-top"]}>
            <Tooltip
              title={arrChangeTypes[changeType].text}
            >
              <IconFont
                type={arrChangeTypes[changeType].iconType}
                onClick={() => {
                  let tchangeType: number = changeType + 1
                  if (tchangeType === arrChangeTypes.length) {
                    tchangeType = 0
                  }
                  setChangeType(tchangeType)
                }}
                style={{ marginRight: '25px', fontSize: '14px' }}
              />
            </Tooltip>
            <IconFont type="iconshangyishou"
              onClick={() => {
                changeSong(false)
              }}
            />
            {state.playInfo.isPlay && songUrl
              ? (
                <IconFont
                  type="iconzanting"
                  className={styles['music-control-play']}
                  onClick={() => {
                    if (songUrl) {
                      audioEle.current.pause()
                      dispatch({ type: 'TOPAUSE' })
                    }
                  }}
                />
              )
              : (
                <IconFont
                  className={styles['music-control-play']}
                  type="iconbofang"
                  onClick={() => {
                    if (songUrl) {
                      audioEle.current.play()
                      dispatch({ type: 'TOPLAY' })
                    }
                  }}
                />
              )}
            <IconFont type="iconxiayishou"
              onClick={() => {
                changeSong(true)
              }}
            />
            <IconFont type="iconci"
              style={{
                marginLeft: '25px',
                fontSize: '14px'
              }}
            />
          </div>
          <div className={styles['music-control-bottom']}>
            <span
              className={styles['progress-sides']}>
              {
                progress > 0
                  ? moment(audioEle?.current?.duration * progress * 1000).format('mm:ss')
                  : '00:00'
              }
            </span>
            <ProgressSlider
              progress0to1={progress}
              canClick={songUrl ? true : false}
              dotStyle={{
                width: '10px',
                height: '10px',
                transform: 'translateX(5px)'
              }}
              onMouseUp={changeCurrentTime} />
            <span className={styles['progress-sides']}>
              {
                audioEle?.current?.duration
                  ? moment(audioEle?.current?.duration * 1000).format('mm:ss')
                  : '00:00'
              }
            </span>
          </div>
        </div>

      </div>
      <div className={styles["footer-right"]}>
        <Tooltip title='暂不支持音效'>
          <IconFont
            type="iconjingyunyinxiaopt-wangyiicon"
            className={styles['icon-margin']}
          />
        </Tooltip>
        <IconFont onClick={() => {
          let tismuted: boolean = isMuted
          if (tismuted) {
            setIsMuted(false)
            audioEle?.current?.volume >= 0
              && (audioEle.current.volume = (voProg || 0.1))
          } else {
            setIsMuted(true)
            audioEle?.current?.volume
              && (audioEle.current.volume = 0)
          }
        }}
          type={isMuted
            ? 'iconmutejingyin'
            : "iconyinliang"}
          className={styles['icon-margin']} />
        <span className={styles['icon-margin']}>
          <ProgressSlider style={{
            width: '150px',
            height: '12px'
          }}
            onProgressChange={volumeProgressChange}
            dotStyle={{
              width: '8px',
              height: '8px',
              transform: 'translateX(4px)'
            }}
            progress0to1={isMuted ? 0 : (voProg || 0.1)}
          />
        </span>
        <IconFont
          className={styles['icon-margin']}
          type="iconbofangliebiao"
          onClick={() => {
            dispatch({
              type: "SET_SHOW"
            })
          }}
        />

      </div>
      <audio
        src={songUrl || ''}
        onError={() => {
          if (state.playInfo.playingId > 0) {
            let thisId: number | null = state.playInfo.playingId
            getsongUrl({ id: thisId }).then((res) => {
              console.log(res?.data[0])
              if (res?.data?.length > 0 && res?.data[0]?.url) {
                setSongUrl(res.data[0].url)
                audioEle.current.play();
              }else{
                console.error('footer getsongUrl出错');
              }
            })
          }
        }}
        onProgress={(event)=>{
          // console.log(event?.target?.buffered?.end(event?.target?.buffered?.length - 1))
        }}
        ref={audioEle}
        onTimeUpdate={onTimeUpdate}
        onEnded={() => {
          console.log('onended',new Date().getTime())
        }}
        onEndedCapture={
          ()=>{
          changeSong(true)
            console.log('onEndedCapture',new Date().getTime())
          }
        }
      ></audio>
    </div>
  );
};
export default Footer;
